<template>
  <section class="page-content">
    <div class="toolbar">
      <el-form :inline="true" :model="params">
        <el-form-item>
          <el-button type="success" size="small" icon="plus" @click="create">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData.data"
      @sort-change="sort"
      border
      style="width: 100%"
      max-height="100%">
      <el-table-column
        prop="id"
        sortable
        width="80"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="title"
        sortable
        label="标题">
      </el-table-column>
      <el-table-column
        prop="goods_id"
        sortable
        label="拼团产品">
        <template slot-scope="scope">
          {{scope.row.goods.name}}
        </template>
      </el-table-column>
      <el-table-column
        prop="time_limit"
        sortable
        label="成团有效期(h)">
      </el-table-column>
      <el-table-column
        prop="needer"
        sortable
        label="需要人数">
      </el-table-column>
       <el-table-column
        prop="needer"
        sortable
        label="是否启动">
        <template slot-scope="scope">
          <i class="el-icon-check" v-if="scope.row.status === 1"></i>
          <i class="el-icon-close" v-if="scope.row.status === 0"></i>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        width="180"
        label="操作">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editRow(scope.row)"
            type="default"
            size="small">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="deleteRow(scope.row)"
            type="danger"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.current_page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="parseInt(tableData.per_page)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total">
      </el-pagination>
    </div>
    <!-- dialog -->
    <el-dialog class="dialog" title="添加拼团" :visible.sync="visible">
      <el-form :model="formData" ref="formData" :rules="formRules"  label-width="120px">
        <el-form-item label="拼团产品" prop="goods_id">
          <el-select
            v-model="formData.goods_name"
            filterable
            remote
            clearable
            placeholder="请输入产品关键词进行检索"
            @change="change"
            :remote-method="getGoods"
            :loading="loading">
            <el-option
              v-for="item in goodsData"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.goods">
         <el-alert
          style="padding-top:0; padding-bottom:0"
          :title="'商场售价：￥' + formData.goods.price + '； 产品库存量：' + formData.goods.stock + formData.goods.unit"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
        </el-form-item>
        <el-form-item label="拼团标题" prop="title">
          <el-input v-model="formData.title" placeholder="拼团标题"></el-input>
        </el-form-item>
        <el-form-item label="有效时间(小时)" prop="time_limit">
          <el-input type="number" v-model="formData.time_limit" placeholder="拼团有效时间（单位：小时）"></el-input>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discount">
          <el-input type="text" v-model="formData.discount" placeholder="请输入优惠的金额"></el-input>
        </el-form-item>
        <el-form-item>
          <el-alert
            style="padding-top:0; padding-bottom:0"
            title="注意：商品售价 = 商品价格 - 优惠金额 ！！！"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </el-form-item>
        <el-form-item label="需要成团人数" prop="needer" required>
          <el-input type="numner" v-model.number="formData.needer" placeholder="需要多少人拼团才能成功(单位：人)"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('formData')" :disabled="editLoading">取 消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleCreateOrEdit('formData')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
  import {generateUrl} from '@/utils/helpers'
  export default {
    data () {
      var checkNeeder = (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('该字段不能为空'))
        }
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value <= 1) {
            callback(new Error('数值必须大于1'))
          } else {
            callback()
          }
        }
      }
      return {
        loading: false,
        tableData: {
          first_page_url: '',
          from: '',
          to: '',
          last_page: '',
          last_page_url: '',
          next_page_url: '',
          prev_page_url: '',
          path: '',
          per_page: 0,
          total: 0,
          data: []
        },
        searchData: {
          title: ''
        },
        params: {
          order_by: 'id',
          order_type: 'desc',
          page_size: 20,
          title: '',
          page: 1
        },
        // dialog
        editLoading: false,
        visible: false,
        getDoodsLoading: false,
        goodsData: [],
        tempData: {
          id: null,
          title: '',
          goods_id: null,
          spec_goods_price_id: 0,
          goods_name: '',
          time_limit: 24,
          discount: '',
          needer: 2,
          goods: null
        },
        formData: {},
        formRules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
            { min: 1, max: 250, message: '长度在 3 到 250 个字符', trigger: 'blur' }
          ],
          time_limit: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          discount: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          needer: [
            { validator: checkNeeder, trigger: 'blur' }
          ],
          goods_id: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
      this._restFormData()
      this._getData()
    },
    watch: {
      params: {
        deep: true,
        handler (newValue) {
          this._getData()
        }
      }
    },
    methods: {
      deleteRow (row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http.delete('/teamActivities/' + row.id).then((response) => {
            this.loading = false
            this.$message.success('删除成功')
            this._getData()
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        })
      },
      change (goodsName) {
        this.goodsData.forEach((el, index) => {
          if (el.name === goodsName) {
            this.formData.goods = el
            this.formData.goods_id = el.id
            this.formData.goods_name = el.name
            this.formData.title = el.name
            this.formData.discount = parseInt(el.price * 0.1)
          }
        })
      },
      cancle (formName) {
        this.$refs[formName].resetFields()
        this.visible = false
      },
      editRow (item) {
        this.formData = Object.assign({}, item)
        this.visible = true
      },
      onSubmit () {
        this.params.name = this.searchData.name
      },
      handleSizeChange (val) {
        this.params.page_size = val
      },
      handleCurrentChange (val) {
        this.params.page = val
      },
      sort (data) {
        let orderType = ''
        if (data.order === 'ascending') {
          orderType = 'asc'
        }
        if (data.order === 'descending') {
          orderType = 'desc'
        }
        this.params.order_type = orderType
        this.params.order_by = data.prop
      },
      create () {
        this._restFormData()
        this.visible = true
      },

      handleCreateOrEdit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http({
              method: this.formData.id === null ? 'post' : 'put',
              url: this.formData.id === null ? '/teamActivities' : '/teamActivities/' + this.formData.id,
              data: this.formData
            }).then((response) => {
              this.$message.success(response.data.message)
              this.editLoading = false
              this.visible = false
              this._getData()
            }).catch((error) => {
              this.editLoading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getGoods (keywords) {
        if (keywords !== '') {
          let url = '/goods?page_size=50&name=' + keywords
          this.getDoodsLoading = true
          this.$http.get(url).then((response) => {
            this.getDoodsLoading = false
            this.goodsData = response.data.data
          }).catch((error) => {
            this.loading = false
            console.log(error)
          })
        }
      },
      _restFormData () {
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        let url = generateUrl('/teamActivities', this.params)
        this.loading = true
        this.$http.get(url).then((response) => {
          this.loading = false
          this.tableData = response.data
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      }
    }
  }
</script>
  
<style scoped>
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 180px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar-uploader-icon:hover {
     border-color: #20a0ff;
  }
  .upload-thumb {
    width: 180px;
    height: 180px;
    display: block;
  }
  .el-select {
    width: 100%;
  }
  .radio-box {
    padding: 2px 0;
  }
  .info {
    color: #777;
    padding-left: 10px;
    font-size: 12px;
  }
  .el-radio-group {
    font-size: 14px;
  }
</style>
